#include <iostream>
#include <string>

using namespace std;

void reverse(int begin, int end, string & s)
{
    for(int left = begin, right = end - 1; left < right; left++, right--)
    {
        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;
    }
}

void eraseEndSpace(string & s)
{
    int spaceEndCount = 0;
    for(int i = s.length() - 1; i >= 0; i--)
    {
        if(s[i] != ' ')
        {
            break;
        }
        spaceEndCount++;
    }
    s.resize(s.length() - spaceEndCount);
}

class Solution 
{
public:
    string reverseWords(string s) 
    {
        eraseEndSpace(s);
        reverse(0, s.length(), s);
        eraseEndSpace(s);

        s += ' ';
        for(int slow = 0, fast = 0; fast < s.length(); fast++)
        {
            if(fast == 0 || (s[fast] != ' ' && s[fast - 1] == ' '))
            {
                slow = fast;
            }
            else if(fast > 0 && s[fast] == ' ' && s[fast - 1] != ' ')
            {
                reverse(slow, fast, s);
            }
        }

        int write = 0;
        for(int read = 0; read < s.length(); read++)
        {
            while(read > 0 && s[read] == ' ' && s[read - 1] == ' ')
            {
                read++;
            }
            s[write] = s[read];
            write++;
        }

        s.resize(write - 1);

        return s;
    }
};

#include <iostream>
#include <vector>
using namespace std;

int main() {
    Solution sol;
    vector<string> testCases = {
        "the sky is blue",
        "  hello world  ",
        "a good   example",
        "",
        "    ",
        "one"
    };

    for (const auto& test : testCases) {
        cout << "原始字符串: \"" << test << "\"" << endl;
        string result = sol.reverseWords(test);
        cout << "反转后: \"" << result << "\"" << endl;
        cout << "------------------------" << endl;
    }
    return 0;
}

